import axios from 'axios'
import $q from 'q'
import {Message} from 'at-ui'
import Route from '../router';



function ajaxRequest(method, url, params, config) {
    if (typeof (url) == 'object') {
        config = url;
        url = null;
    }

    if (!config) {
        config = {}
    }

    if (method == "get" || method == "delete") {
        config.params = params
    } else {
        config.data = params;
    }
    config.method = method
    config.url = url
    let defer = $q.defer()
    axios({
        method: config.method,
        url: config.url,
        params: config.params || null,
        data: config.data || null,
        baseURL: 'http://ma.ethan.pub/jiuetongWeb/',
        withCredentials: true,
        transformRequest: [function (data, headers) {
            if (!data) {
                return data;
            }
            if (data && config.isJson) {
                headers['Content-Type'] = 'application/json;charset=utf-8';
                return JSON.stringify(data);
            } else if (data && config.isFile) {
                headers['Content-Type'] = 'multipart/form-data';
                return data;
            } else {
                headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
                let keys2 = Object.keys(data);
                /* 这里就是把json变成url形式，并进行encode */
                let newData = encodeURI(keys2.map(name => `${name}=${data[name]}`).join('&'));
                return newData;
            }

        }],
    }).then(res => {
        if (!res.data || !res.data.data) {
            console.log("响应结构不存在data字段");
            if (res.data.code == 200) {
                defer.resolve(res.data.data, res.data, res)
            } else {
                Message.error(res.data.message)
                defer.reject(res.data)
            }
        } else {
            if (res.data.code == 200) {
                defer.resolve(res.data.data, res.data, res)
            } else {
                let err = res.data
                if (err.code == 500) {
                    console.log("服务器错误:" + err.msg)
                } else if (err.code == 400) {
                    console.log(err.msg)
                } else if (err.code == 401) {
                    console.log(err.msg)
                }
                defer.reject(res.data)
            }
        }
    }).catch(err => {
        defer.reject(err)
    })
    return defer.promise
}

export default {

    get: function (url, params, config) {
        return ajaxRequest("get", url, params, config)
    },

    post: function (url, params, config) {
        return ajaxRequest("post", url, params, config)
    }
}

